﻿namespace Catel.Articles._08___WP7_Camera.Data
{
    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Windows.Media.Imaging;

    /// <summary>
    /// Demo implementation of the <see cref="IPhotoRepository"/>.
    /// </summary>
    public class DemoPhotoRepository : IPhotoRepository
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DemoPhotoRepository"/> class.
        /// </summary>
        public DemoPhotoRepository()
        {
            Photos = new List<BitmapSource>();

            for (int i = 0; i < 5; i++)
            {
                WebClient client = new WebClient();
                client.OpenReadCompleted += OnWebClientOpenReadCompleted;
                client.OpenReadAsync(new Uri("http://lorempixum.com/400/200"));
            }
        }

        /// <summary>
        /// Gets the photos.
        /// </summary>
        /// <value>The photos.</value>
        public List<BitmapSource> Photos { get; private set; }

        /// <summary>
        /// Called when the <see cref="WebClient.OpenReadCompleted"/> event occurs.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Net.OpenReadCompletedEventArgs"/> instance containing the event data.</param>
        private void OnWebClientOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            ((WebClient) sender).OpenReadCompleted -= OnWebClientOpenReadCompleted;

            var image = new BitmapImage();
            image.SetSource(e.Result);

            Photos.Add(image);
        }
    }
}
